package com.gy.paidao.create;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Camera;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.duanqu.qupai.android.app.QupaiDraftManager;
import com.duanqu.qupai.android.app.QupaiServiceImpl;
import com.duanqu.qupai.editor.EditorResult;
import com.duanqu.qupai.engine.session.MovieExportOptions;
import com.duanqu.qupai.engine.session.VideoSessionCreateInfo;
import com.duanqu.qupai.recorder.EditorCreateInfo;
import com.gy.paidao.BaseActivity;
import com.gy.paidao.MyApplication;
import com.gy.paidao.R;
import com.gy.paidao.bean.BaseBean;
import com.gy.paidao.main.MapSearchActivity;
import com.gy.paidao.util.Contant;
import com.gy.paidao.util.FileUtils;
import com.gy.paidao.util.LogUtil;
import com.gy.paidao.util.PhotoUtil;
import com.gy.paidao.util.SPHelper;
import com.gy.paidao.util.Urls;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 作者：gy on 16/4/15
 * 说明：创建一个新的泡泡
 */
public class CreateBabbleActivity extends BaseActivity {

    private static String PICTURE = "image";
    private static String VIDEO = "video";
    private LinearLayout llSelect, llCreate;//选择方式
    private ImageView imgPhoto, imgVideo, imgCancel;
    private ImageView imgLeft;
    private EditText etTitle, etContent;
    private TextView tvClose, tvLoc, tvNum, tvCreate;
    private final EditorCreateInfo _CreateInfo = new EditorCreateInfo();
    private int beautySkinProgress;
    private String videoPath, tempPath;
    private static int QUPAI_RECORD_REQUEST = 1;
    private static final int PHOTO_REQUEST_TAKEPHOTO = 101;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 102;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 103;// 结果
    private File tempFile;// 创建一个以当前时间为名称的文件
    private Bitmap bitmap;
    private Uri photoUri;// 照片uri
    private String firstPath;//第一张截图
    private String lastPathSegment, mediaType, description, title, userLoginID;
    private String imgType = "png", vidoType = "mp4", fileType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_babble);
        setViews();

    }

    @Override
    protected void initVariable() {
        userLoginID = SPHelper.getInstance(this).getStringData("userLoginID", null);
        tempFile = new File(getPhotoFileName());
    }

    @Override
    protected void setTitleViews() {

    }

    @Override
    protected void setViews() {
        llSelect = (LinearLayout) findViewById(R.id.activity_create_ll_select);
        llCreate = (LinearLayout) findViewById(R.id.activity_create_ll_create);
        imgPhoto = (ImageView) findViewById(R.id.activity_create_img_photo);
        imgVideo = (ImageView) findViewById(R.id.activity_create_img_video);
        imgCancel = (ImageView) findViewById(R.id.activity_create_img_cancel);
        imgLeft = (ImageView) findViewById(R.id.activity_create_img_left);
        tvClose = (TextView) findViewById(R.id.activity_create_tv_close);
        tvLoc = (TextView) findViewById(R.id.activity_create_tv_loc);
        tvNum = (TextView) findViewById(R.id.activity_create_tv_number);
        tvCreate = (TextView) findViewById(R.id.activity_create_tv_create);
        etTitle = (EditText) findViewById(R.id.activity_create_et_name);
        etContent = (EditText) findViewById(R.id.activity_create_et_content);

        tvLoc.setOnClickListener(this);
        imgPhoto.setOnClickListener(this);
        imgVideo.setOnClickListener(this);
        imgCancel.setOnClickListener(this);
        imgLeft.setOnClickListener(this);
        tvClose.setOnClickListener(this);
        tvCreate.setOnClickListener(this);

        etContent.addTextChangedListener(contentWatcher);
        if (!TextUtils.isEmpty(MyApplication.ADDRESS)) {
            tvLoc.setText(MyApplication.ADDRESS);
        }
    }

    @Override
    protected void doClickAction(int viewId) {
        super.doClickAction(viewId);
        switch (viewId) {
            case R.id.activity_create_tv_loc://选择位置
                intent = new Intent(this, MapSearchActivity.class);
                startActivityForResult(intent, 105);
                break;
            case R.id.activity_create_img_photo:
                mediaType = PICTURE;
                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
                startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
                break;
            case R.id.activity_create_img_video:
                mediaType = VIDEO;
                startRecordActivity();
                break;
            case R.id.activity_create_img_cancel:
            case R.id.activity_create_img_left:
            case R.id.activity_create_tv_close:
                finish();
                break;
            case R.id.activity_create_tv_create:
                title = etTitle.getText().toString().trim();
                description = etContent.getText().toString().trim();
                if (TextUtils.isEmpty(title)) {
                    title = "Bubble Name";
                }
                dorequestComplete();
                break;
        }
    }

    TextWatcher contentWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!TextUtils.isEmpty(s.toString())) {
                if (s.toString().length() <= 100) {
                    int num = 100 - s.toString().length();
                    tvNum.setText(num + "");
                } else {
                    tvNum.setText(0 + "");
                    String content = s.toString();
                    etContent.setText(content.substring(0, 100));
                }

            } else {
                tvNum.setText("100");
            }
        }
    };

    private void startRecordActivity() {
        //美颜参数:1-100.这里不设指定为80,这个值只在第一次设置，之后在录制界面滑动美颜参数之后系统会记住上一次滑动的状态
        beautySkinProgress = 100;

        /**
         * 压缩参数，可以自由调节
         */
        MovieExportOptions movie_options = new MovieExportOptions.Builder()
                .setVideoProfile("high")
                .setVideoBitrate(Contant.DEFAULT_BITRATE)
                .setVideoPreset(Contant.DEFAULT_VIDEO_Preset).setVideoRateCRF(Contant.DEFAULT_VIDEO_RATE_CRF)
                .setOutputVideoLevel(Contant.DEFAULT_VIDEO_LEVEL)
                .setOutputVideoTune(Contant.DEFAULT_VIDEO_TUNE)
                .configureMuxer(Contant.DEFAULT_VIDEO_MOV_FLAGS_KEY, Contant.DEFAULT_VIDEO_MOV_FLAGS_VALUE)
                .build();

        /**
         * 界面参数
         */
        VideoSessionCreateInfo create_info = new VideoSessionCreateInfo.Builder()
                .setOutputDurationLimit(Contant.DEFAULT_DURATION_MAX_LIMIT)
                .setOutputDurationMin(Contant.DEFAULT_DURATION_LIMIT_MIN)
                .setMovieExportOptions(movie_options)
                .setBeautyProgress(beautySkinProgress)
                .setBeautySkinOn(false)//美颜是否开启
                .setCameraFacing(Camera.CameraInfo.CAMERA_FACING_BACK)//Camera.CameraInfo.CAMERA_FACING_FRONT 前置摄像头
                .setVideoSize(360, 640)
                .setCaptureHeight(getResources().getDimension(R.dimen.qupai_recorder_capture_height_size))
                .setBeautySkinViewOn(true)//美颜是否显示
                .setFlashLightOn(true)//闪光灯是否显示
                .setTimelineTimeIndicator(true)//时间是否显示
                .build();

        _CreateInfo.setSessionCreateInfo(create_info);
        _CreateInfo.setNextIntent(null);
        _CreateInfo.setOutputThumbnailSize(360, 640);//输出图片宽高
        videoPath = FileUtils.newOutgoingFilePath(this);
        _CreateInfo.setOutputVideoPath(videoPath);//输出视频路径
        _CreateInfo.setOutputThumbnailPath(videoPath + ".png");//输出图片路径
        QupaiServiceImpl qupaiService = new QupaiServiceImpl.Builder()
                .setEditorCreateInfo(_CreateInfo).build();
        qupaiService.showRecordPage(this, QUPAI_RECORD_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 105) {
            tvLoc.setText(data.getStringExtra("loc"));
        }
        switch (requestCode) {
            case RESULT_OK:
            case RESULT_FIRST_USER:
                if (data == null) {
                    return;
                }
                llSelect.setVisibility(View.GONE);
                llCreate.setVisibility(View.VISIBLE);
                EditorResult result = new EditorResult(data);
                //得到视频path，和缩略图path的数组，返回十张缩略图,和视频时长
                String path = result.getPath();
                String[] nail = result.getThumbnail();
                long duration = result.getDuration();
                videoPath = path;

                if (nail != null && nail.length > 0) {
                    firstPath = nail[0];
                } else {
                    firstPath = "";
                }
                firstPath = videoPath + ".png";
                LogUtil.e(videoPath + "-----" + firstPath);
                //删除草稿
                QupaiDraftManager draftManager = new QupaiDraftManager();
                draftManager.deleteDraft(data);
                break;
            case PHOTO_REQUEST_CUT:
                if (data != null)
                    setPicToView(data);
                break;
            case PHOTO_REQUEST_TAKEPHOTO:
                if (tempFile == null) {
                    showToast("操作失败,请重试...");
                    return;
                }
                tempPath = tempFile.getPath();
                int degree = getBitmapDegree(tempPath);
                bitmap = PhotoUtil.handlerBitmap(tempPath, degree);
                LogUtil.e("bitmap:"+bitmap);
                if(bitmap != null){
                    tempFile = null;
                    llSelect.setVisibility(View.GONE);
                    llCreate.setVisibility(View.VISIBLE);
                }
                break;

            case PHOTO_REQUEST_GALLERY:
                setImageProve(data);
                break;
        }

    }

    private void dorequestComplete() {
        showLoading();
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(30, TimeUnit.SECONDS);
        client.setReadTimeout(30, TimeUnit.SECONDS);
        client.setWriteTimeout(30, TimeUnit.SECONDS);

        byte[] b = null;
        byte[] first = null;
        if (PICTURE.equals(mediaType)) {
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
            b = baos.toByteArray();
            fileType = imgType;
        } else if (VIDEO.equals(mediaType)) {
            try {
                FileInputStream fileInputStream = new FileInputStream(videoPath);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024 * 10];
                int len = 0;
                while ((len = fileInputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                b = outputStream.toByteArray();
                outputStream.close();

                if (!TextUtils.isEmpty(firstPath)) {
                    fileInputStream = new FileInputStream(firstPath);
                    outputStream = new ByteArrayOutputStream();
                    buffer = new byte[1024 * 10];
                    len = 0;
                    while ((len = fileInputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, len);
                    }
                    first = outputStream.toByteArray();
                    outputStream.close();
                }
                fileType = vidoType;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        RequestBody fileBody = null, firstBody = null;
        fileBody = RequestBody.create(MediaType.parse(guessMimeType("name")), b);
        if (first != null) {
            firstBody = RequestBody.create(MediaType.parse(guessMimeType("name")), first);
        }
        MultipartBuilder multipartBuilder = new MultipartBuilder().type(MultipartBuilder.FORM)
                .addFormDataPart("latitude", MyApplication.CURRENT_Y + "")
                .addFormDataPart("longitude", MyApplication.CURRENT_X + "")
                .addFormDataPart("mediaType", mediaType + "")
                .addFormDataPart("position", tvLoc.getText().toString().trim() + "")
                .addFormDataPart("description", description + "")
                .addFormDataPart("title", title + "")
                .addFormDataPart("areaCode", MyApplication.USERID + "")
                .addPart(Headers.of("Content-Disposition", "form-data; name=\"file\";" +
                        "filename=\"" + fileType + "\""), fileBody);
        if (firstBody != null) {
            multipartBuilder.addPart(Headers.of("Content-Disposition", "form-data; name=\"thumbnail\";" +
                    "filename=\"" + imgType + "\""), firstBody);
        }
        Request request = new Request.Builder()
                .url(Urls.url_common+"/activity/issueActivity")
                .post(multipartBuilder.build())
                .addHeader("Cookie", "userLoginID=" + userLoginID)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                LogUtil.e("泡泡上传失败");
                dismissLoading();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                String json = response.body().string();
                LogUtil.e(json);
                dismissLoading();
                BaseBean baseBean = gson.fromJson(json, BaseBean.class);
                if (baseBean.success) {
                    CreateBabbleActivity.this.sendBroadcast(new Intent("new_bubble"));
                    CreateBabbleActivity.this.finish();
                } else {
                    if(!TextUtils.isEmpty(baseBean.errMsg)){
                        Message msg = new Message();
                        msg.what = 0;
                        msg.obj = baseBean.errMsg;
                        toastHandler.sendMessage(msg);
                    }
                }

            }
        });
    }

    private Handler toastHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String toast = (String) msg.obj;
            showToast(toast);
        }
    };

    private static String guessMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(path);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }

    // 将进行剪裁后的图片显示到UI界面上
    private void setPicToView(Intent picdata) {
        Bundle bundle = picdata.getExtras();
        if (bundle != null) {
            Bitmap photo = bundle.getParcelable("data");
            bitmap = photo;

        }
    }

    /**
     * 读取图片的旋转的角度
     *
     * @param path 图片绝对路径
     * @return 图片的旋转角度
     */
    private int getBitmapDegree(String path) {
        int degree = 0;
        try {
            // 从指定路径下读取图片，并获取其EXIF信息
            ExifInterface exifInterface = new ExifInterface(path);
            // 获取图片的旋转信息
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 将图片按照某个角度进行旋转
     *
     * @param bm     需要旋转的图片
     * @param degree 旋转角度
     * @return 旋转后的图片
     */
    public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
        Bitmap returnBm = null;

        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                    bm.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }

    private void setImageProve(Intent data) {
        if (data == null) {
            showToast("操作失败,请重试...");
            return;
        }
        photoUri = data.getData();
        try {
            ContentResolver resolver = getContentResolver();

            if (resolver.getType(photoUri) != null
                    && PhotoUtil.isImageFormat(resolver.getType(photoUri))) {

            } else {
                showToast("操作失败,请重试...");
                return;
            }
            Cursor cursor = this.getContentResolver().query(photoUri, null,
                    null, null, null);
            cursor.moveToFirst();
            String path = "";
            try {
                path = cursor.getString(1);
            } catch (Exception e) {
            }
            cursor.close();
            if (PhotoUtil.isImageFormat(resolver.getType(photoUri))) {
            } else {
                InputStream in = resolver.openInputStream(photoUri);
            }
            int degree = getBitmapDegree(path);
            bitmap = PhotoUtil.handlerBitmap(tempPath, degree);
//            bitmap = PhotoUtil.getSizedBitmap(1280, 720, path);
        } catch (Exception e) {
            e.printStackTrace();
            showToast("操作失败,请重试...");
            return;
        }
        tempPath = photoUri.getPath();
        if (tempPath == null) {
            showToast("操作失败,请重试...");
            return;
        }
        if (tempPath.endsWith(".jpg") || tempPath.endsWith(".png")
                || tempPath.endsWith(".jpeg")) {

        } else if (!tempPath.startsWith("/mnt/")) {
            String[] proj = {MediaStore.Images.Media.DATA};
            // Sysout.i("img path ===", tempPath);
            Cursor actualimagecursor = managedQuery(photoUri, proj, null, null,
                    null);
            if (actualimagecursor != null) {
                int actual_image_column_index = actualimagecursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                actualimagecursor.moveToFirst();
                tempPath = actualimagecursor
                        .getString(actual_image_column_index);
            } else {
                showToast("操作失败,请重试...");
                return;
            }
        }
    }

    private String getPhotoFileName() {

        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyyMMdd_HHmmss");
        return "/storage/emulated/0/Android/data/com.gy.paidao/files/mounted/qupaiVideo/"+ dateFormat.format(date) + ".jpg";
    }


}
